package com.duke.shaking.interaction;

import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;

import com.duke.shaking.BaseActivity;
import com.duke.shaking.R;
import com.duke.shaking.ShakeTabActivity;
import com.duke.shaking.ShakeTabEvent;
import com.duke.shaking.more.VIPUpgradeActivity;
import com.duke.shaking.net.AsyncHttpResponseWithResultHandler;
import com.duke.shaking.net.MessageFetcher;
import com.duke.shaking.net.MessageFetcher.MessageFetchListener;
import com.duke.shaking.net.NetUtils;
import com.duke.shaking.pojo.ChatFriend;

public class ChatFriendsActivity extends BaseActivity 
			implements ShakeTabEvent, 
			ChatFriendSelectListener, 
			OnItemLongClickListener,
			MessageFetchListener{

	private ChatFriendsListView listView;
	private int longClickIndex = -1;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chatfriends);
        listView = (ChatFriendsListView)this.findViewById(R.id.lst_chatfriends);
        if (listView != null) {
        	listView.setSelectListener(this);
        	listView.setOnItemLongClickListener(this);
        	listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
                public void onCreateContextMenu(ContextMenu menu, View v,
                	ContextMenu.ContextMenuInfo menuInfo) {
                    //menu.setHeaderTitle("");
                	popupLongClickMenu(menu);
                }
            });
        }
	}
	
	private void popupLongClickMenu(ContextMenu menu) {
		if (longClickIndex >= 0) {
    		ChatFriend f = listView.getFriendByPosition(longClickIndex);
    		if (f != null 
    			&& (!(f.isNewFriend() != null && f.isNewFriend())
    			|| (me.getLevel() != null && me.getLevel() > 0))) {
    			menu.add(0, 100, 0, R.string.tip_clear_friend_msg);
    		}
    		menu.add(0, 101, 0, R.string.tip_delete_friend);
    		menu.add(0, 102, 0, R.string.cancel);
    	}
	}
	
	protected void onStart() {
		
		super.onStart();
		MessageFetcher.getShared().addListener(this);
		if (listView != null) {
			listView.reloadData();
		}
	}
	
	protected void onStop() {
		super.onStop();
		MessageFetcher.getShared().removeListener(this);
	}
	
	private void removeFriend(int index) {
		
		AsyncHttpResponseWithResultHandler responseHandler = new AsyncHttpResponseWithResultHandler(){
			
        	@Override
			public void onResultSuccess(String response) {
				// TODO Auto-generated method stub
				super.onResultSuccess(response);
				listView.removeItemAtPosition(longClickIndex);
			}

			@Override
			public void onResultFailure(String result) {
				// TODO Auto-generated method stub
				super.onResultFailure(result);
				toast(R.string.err_delete_friend);
			}
        };
        
        ChatFriend f = listView.getFriendByPosition(index);
        if (f != null) {
        	NetUtils.deleteFriend(this, responseHandler, f.getUserId());
        }
	}
	
	@Override
    public boolean onContextItemSelected(MenuItem item) {
		
		switch(item.getItemId()) {
		case 100:
			if (longClickIndex >= 0) {
				listView.clearMessageOfFriend(longClickIndex);
			}
			break;
		case 101:
			if (longClickIndex >= 0) {
				removeFriend(longClickIndex);
			}
			break;
		case 102:
			break;
		}
		longClickIndex = -1;
        return super.onContextItemSelected(item);
    }
	
	public void onActive(ShakeTabActivity tabs) {
		info("ChatFriendsActivity.onActive");
		tabs.initTitle(0,
				0,
				0,
				0,
				R.string.message);
	}

	public void onBackBtn() {
		// TODO Auto-generated method stub

	}

	public void onLeftBtn() {
		// TODO Auto-generated method stub

	}

	public void onRightBtn() {
		// TODO Auto-generated method stub
		new AlertDialog.Builder(this)
			.setMessage(R.string.confirm_delete_all_friends)
			.setPositiveButton(R.string.ok, new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					listView.removeAllItems();
				}
				
			})
			.setNegativeButton(R.string.cancel, null)
		    .show();
	}

	private void gotoBuyService(String msg) {
		Builder builder = new Builder(this);
		builder.setMessage(msg).setPositiveButton(R.string.btn_upgrade_now, 
			new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					go(VIPUpgradeActivity.class);
					dialog.dismiss();
				}
			});
			builder.setNegativeButton(R.string.cancel, new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
		
		AlertDialog alert = builder.create();
		alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        alert.show();
	}
	
	public void onSelected(ChatFriend friend) {
		info("on chat friend selected");
		if (friend.isNewFriend() && 
			friend.getUnreadMessages() > 0 &&
			(me.getLevel() == null || me.getLevel() <= 0)) {
			int newFriends = 0, unreadMsgs = 0;
			List<ChatFriend> friends = listView.getFriends();
			if (friends != null) {
				for(ChatFriend f : friends) {
					if (f != null) {
						if (f.isNewFriend()) {
							newFriends ++;
							unreadMsgs += f.getUnreadMessages();
						}
					}
				}
			}
			String msg = String.format(Locale.CHINA, 
					getString(R.string.alert_open_unread_msg), 
					newFriends, unreadMsgs);
			gotoBuyService(msg);
		}
		else {
			go(ChatActivity.class, "friend", friend);
		}
	}

	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position,
			long id) {
		// TODO Auto-generated method stub
		longClickIndex = position;
		return false;
	}

	public void onNewMessageArrived() {
		// TODO Auto-generated method stub
		if (listView != null) {
			listView.reloadData();
		}
	}

}
